package com.qf.base.result;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * projectName: automation
 *
 * @author dongshihao
 * Date:2021/9/24   22:02
 * description:
 */
public class R {
    /**
     * 这是响应代码
     */
    private int code;
    /**
     * 这是响应摘要的休息
     */
    private String msg;
    /**
     * 这里使用object 类型
     */
    private Object result;


    public static final int OK_200 = 200;
    public static final int E_500 = 500;
    public static final int IS_OK = 100;

    public boolean isOK() {
        if (this.code / IS_OK == 2) {
            return true;
        }
        return false;
    }

    public R setCode(int code) {
        this.code = code;
        return this;
    }
    public R setMsg(String msg) {
        this.msg = msg;
        return this;
    }
    public R setResult(Object result) {
        this.result = result;
        return this;
    }

    /**
     * 方法重载
     */

    public R setResult(String key, Object value) {
        if (result == null) {
            JSONObject result = new JSONObject();
            result.put(key, value);
            this.result = result;
        } else {
            if (result instanceof JSONObject) {
                ((JSONObject) result).put(key, value);
            }
            if (result instanceof Map) {
                ((Map) result).put(key, value);
            }
        }
        return this;
    }
    /**
     * 调用成功的方法
     */
    public static R ok(){
        R r=new R().setCode(OK_200).setMsg("请求成功");
        return r;
    }
    public static R ok(int code){
        R r=new R().setCode(code).setMsg("请求成功");
        return r;
    }
    public static R ok(String msg){
        R r=new R().setCode(OK_200).setMsg(msg);
        return r;
    }
    public static R ok(int code,String msg){
        R r=new R().setCode(code).setMsg(msg);
        return r;
    }
    public static R ok(Object data){
        return ok().setResult(data);
    }

    /**
     * 调用失败的方法
     */
    public static R error(){
        R r=new R().setCode(E_500).setMsg("请求失败");
        return r;
    }
    public static R error(int code){
        R r=new R().setCode(code).setMsg("请求成功");
        return r;
    }
    public static R error(String msg){
        R r=new R().setCode(E_500).setMsg(msg);
        return r;
    }
    public static R error(int code,String msg){
        R r=new R().setCode(code).setMsg(msg);
        return r;
    }
    public static R error(Object data){
        return ok().setResult(data);
    }

    public int getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
    public Object getResult() {
        return result;
    }




    public String toJsonString(R r){
        return JSONObject.toJSONString(r);

    }

    @Override
    public String toString() {
        return toJsonString(this);
    }
}
